//
//  MyCircleEightButton.cpp
//  CanYouDoIt
//
//  Created by hoangtx on 7/11/13.
//
//

#include "MyCircleEightButton.h"
#include "MyUtilities.h"

bool MyCircleEightButton::init(){
    MyRotatingButton::init();
    currentRotatingState = 0;

    distanceTravel = 0;
    return true;
}

MyCircleEightButton* MyCircleEightButton::create(const char *fileName, double mX, double mY, double mWidth, double mHeight){
    MyCircleEightButton* button = MyCircleEightButton::create();
    button->setPosition(ccp(mX,mY));
    button->buttonSize = CCSizeMake(mWidth, mHeight);
    button->sprite = CCSprite::create(fileName);
    button->sprite->setAnchorPoint(ccp(0,0));
    button->sprite->setScaleX(mWidth/button->sprite->getContentSize().width);
    button->sprite->setScaleY(mHeight/button->sprite->getContentSize().height);
    button->sprite->setPosition(ccp(0,0));
    button->sprite->setColor(button->normalColor);
    button->addChild(button->sprite);
    button->originalPoint = button->getPosition();
    return button;
    
}

void MyCircleEightButton::setCircle(cocos2d::CCPoint mOrigin, double mRadius){
    MyRotatingButton::setCircle(mOrigin, mRadius);
    topOrigin = mOrigin;
    botOrigin = ccp(topOrigin.x,topOrigin.y-2*radius);
}

void MyCircleEightButton::resetState(){
    angleVelocity = originalVelocity;
    distanceTravel = 0;
    randomDirection();
    setPosition(originalPoint);
    
}

void MyCircleEightButton::reverse(){
    if(currentRotatingState==0){
        currentRotatingState=1;
        originPoint = botOrigin;


    }else{
        currentRotatingState=0;
        originPoint = topOrigin;


    }
    distanceTravel = 0;
    currentAngle = - currentAngle;
    angleVelocity = -angleVelocity;
}

void MyCircleEightButton::randomDirection(){
    currentRotatingState = rand()%2;
    int veloRandom = rand()%2;
    if(veloRandom==0){
        angleVelocity = -angleVelocity;
    }
    if(currentRotatingState==0){
        currentAngle = -M_PI/2;
        originPoint = topOrigin;
    }else{
        currentAngle = M_PI/2;
        originPoint = botOrigin;
    }
}

void MyCircleEightButton::handleUpdate(float dt){
    currentAngle+=angleVelocity;
    distanceTravel+=MyUtilities::triTuyetDoi(angleVelocity);
    if(distanceTravel>=M_PI*2){
        reverse();
    }

    CCPoint destinationPoint = MyUtilities::rotateAroundPoint(originPoint, currentAngle, radius);
    
    this->setPosition(destinationPoint);
}